import React, { useEffect } from 'react';
import { connect } from 'umi';
import { useTRState } from '#/utils/trHooks.jsx';
// components
import { Tabs } from 'antd';
import { PageLoading } from '@/components/index.js';
import PowerForecastTab from './PowerForecastTab';
import PowerForecastImpact from './PowerForecastImpact';
import { TRDefault } from '@/components/index.js';
import { getTreeByCodes } from '@/utils';
// api
import { HttpCode } from '#/utils/contacts.js';
import { queryMarketList } from './services.js';

const { TabPane } = Tabs;

const PowerForecast = ({ menuCode = '', buttonPermissions = [] }) => {
  const [state, setState] = useTRState({
    error: '',
    loading: true,
    power: [], // 数据权限
  });

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    setState({ loading: true });
    let error = '';
    let power = [];
    let allKeys = [];
    const res = await queryMarketList(menuCode);
    if (res?.statusCode === HttpCode.SUCCESS) {
      const { treeOptions, allKeys: _allKeys } = getTreeByCodes(
        ['market', 'group', 'station'],
        res.json,
      );
      power = treeOptions;
      allKeys = _allKeys;
    } else {
      error = res?.message;
    }
    setState({
      error,
      power,
      allKeys,
      loading: false,
    });
  };

  if (state.loading) return <PageLoading />;
  if (state.error) return <TRDefault type="error" message={state.error} />;
  if (!state.power.length) return <TRDefault type="lock" />;
  return (
    <div className={'tabPage'}>
      <Tabs defaultActiveKey={'1'}>
        <TabPane tab="市场化运维" key="1">
          <PowerForecastTab
            power={state.power}
            allKeys={state.allKeys}
            buttonPermissions={buttonPermissions}
          />
        </TabPane>
        <TabPane tab="功率预测评价" key="2">
          <PowerForecastImpact power={state.power} buttonPermissions={buttonPermissions} />
        </TabPane>
      </Tabs>
    </div>
  );
};

export default connect(({ global }) => ({
  menuCode: global?.configure?.menuCode,
  buttonPermissions: global?.configure?.buttonPermissions,
}))(PowerForecast);
